package one.bugu.android.demon.ui.widget;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.graphics.drawable.ColorDrawable;
import android.text.Editable;
import android.text.SpannableString;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.juefeng.android.framework.LKUtil;

import java.util.ArrayList;

import one.bugu.android.demon.R;
import one.bugu.android.demon.bean.ChooseDataBean;
import one.bugu.android.demon.bean.snatch.SnatchPeriodBean;
import one.bugu.android.demon.ui.adapter.snatch.ChooseSnatchAdapter;
import one.bugu.android.demon.util.MyTextUtils;
import one.bugu.android.demon.util.ScreenUtils;

/**
 * 夺宝选择弹窗
 */
public class SelectPopupWindow extends PopupWindow {

    private Activity mActivity;
    private View view;
    private ImageView iv_popup_close;
    private TextView tv_items_title;
    private TextView tv_items_num;
    private TextView tv_items_mark;
    private TextView tv_items_subtract;
    private EditText et_items_num;
    private TextView tv_items_add;
    private TextView tv_items_info;
    private GridViewForScrollView gv_items_choose;
    private TextView tv_items_balance;
    private LinearLayout ll_container;
    private TextView tv_items_btn;
    private ImageView iv_items_image;
    private ArrayList<ChooseDataBean> chooseData;
    private SnatchPeriodBean.DataBean snatchData;
    private final int canBought;


    public SelectPopupWindow(Activity activity, SnatchPeriodBean.DataBean snatchData, OnOrdersClickListener ordersClickListener) {
        this.mActivity = activity;
        this.ordersClickListener = ordersClickListener;
        this.snatchData = snatchData;

        canBought = snatchData.getGoodsNum() - snatchData.getBoughtNum();

        view = View.inflate(activity, R.layout.popup_select_layout, null);
        iv_popup_close = (ImageView) view.findViewById(R.id.iv_popup_close);
        tv_items_title = (TextView) view.findViewById(R.id.tv_items_title);
        tv_items_num = (TextView) view.findViewById(R.id.tv_items_num);
        tv_items_mark = (TextView) view.findViewById(R.id.tv_items_mark);
        tv_items_subtract = (TextView) view.findViewById(R.id.tv_items_subtract);
        et_items_num = (EditText) view.findViewById(R.id.et_items_num);
        tv_items_add = (TextView) view.findViewById(R.id.tv_items_add);
        tv_items_info = (TextView) view.findViewById(R.id.tv_items_info);
        gv_items_choose = (GridViewForScrollView) view.findViewById(R.id.gv_items_choose);
        tv_items_balance = (TextView) view.findViewById(R.id.tv_items_balance);
        ll_container = (LinearLayout) view.findViewById(R.id.ll_container);
        tv_items_btn = (TextView) view.findViewById(R.id.tv_items_btn);
        iv_items_image = (ImageView) view.findViewById(R.id.iv_items_image);

        iv_popup_close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SelectPopupWindow.this.dismiss();
            }
        });

        //初始化popupwindow
        initPopupWindow();
        initPopupChooseData();
        //设置数据
        setViewData();
        //事件处理
        initEvent();
    }

    private void initPopupWindow() {
        //设置SelectPicPopupWindow的View
        this.setContentView(view);
        //设置SelectPicPopupWindow弹出窗体的宽
        this.setWidth(LayoutParams.FILL_PARENT);
        //设置SelectPicPopupWindow弹出窗体的高
        this.setHeight(LayoutParams.WRAP_CONTENT);
        //设置SelectPicPopupWindow弹出窗体可点击
        this.setFocusable(true);
        //设置SelectPicPopupWindow弹出窗体动画效果
        this.setAnimationStyle(R.style.anim_bottom_popupwindow);
        //实例化一个ColorDrawable颜色为半透明
        ColorDrawable dw = new ColorDrawable();
        //设置SelectPicPopupWindow弹出窗体的背景
        this.setBackgroundDrawable(dw);
        //mMenuView添加OnTouchListener监听判断获取触屏位置如果在选择框外面则销毁弹出框
        view.setOnTouchListener(new View.OnTouchListener() {
            public boolean onTouch(View v, MotionEvent event) {
                int height = view.findViewById(R.id.pop_layout).getTop();
                int y = (int) event.getY();
                if (event.getAction() == MotionEvent.ACTION_UP) {
                    if (y < height) {
                        dismiss();
                    }
                }
                return true;
            }
        });

        this.setOnDismissListener(new OnDismissListener() {
            @Override
            public void onDismiss() {
                backgroundAlpha(1f);
            }
        });
    }

    /**
     * 初始化选择弹窗
     */
    private void initPopupChooseData() {
        chooseData = new ArrayList<>();


        chooseData.add(new ChooseDataBean("5", getClickState(5)));
        chooseData.add(new ChooseDataBean("10", getClickState(10)));
        chooseData.add(new ChooseDataBean("20", getClickState(20)));
        chooseData.add(new ChooseDataBean("50", getClickState(50)));
        chooseData.add(new ChooseDataBean("100", getClickState(100)));
        chooseData.add(new ChooseDataBean("200", getClickState(200)));
        chooseData.add(new ChooseDataBean("500", getClickState(500)));
        chooseData.add(new ChooseDataBean("全部", true));

        ChooseSnatchAdapter mAdapter = new ChooseSnatchAdapter(mActivity, chooseData);
        gv_items_choose.setAdapter(mAdapter);
    }

    /**
     * 判断按钮是否可点击
     *
     * @param inputNum
     * @return
     */
    private boolean getClickState(int inputNum) {
        boolean flag = false;
        int goodsPrice = snatchData.getGoodsPrice();
        double myBgt = snatchData.getBgtNum();
        if ((inputNum * goodsPrice) <= myBgt) {
            flag = true;
        }
        return inputNum <= canBought && flag;
    }

    /**
     * 设置数据
     */
    @SuppressLint("SetTextI18n")
    private void setViewData() {

        et_items_num.setText("1");

        tv_items_title.setText(snatchData.getGoodsName());
        tv_items_mark.setText("第" + snatchData.getPeriodNo() + "期");
        LKUtil.getImageLoader().loadImage(snatchData.getGoodsImg(), iv_items_image);

        String text = snatchData.getGoodsPrice() + "BGT/份";
        SpannableString content = MyTextUtils.getInstance().setAutoTextSize(text, 1, text.length(), ScreenUtils.spToPx(mActivity, 14));
        tv_items_num.setText(content);

        String info = "本期最高出售" + snatchData.getGoodsNum() + "份，已售出" + snatchData.getBoughtNum() + "份";
        SpannableString infoText = MyTextUtils.getInstance().setAutoTextColor(info, "[0-9]{1,}份", "#FF5453");
        tv_items_info.setText(infoText);

        String bgt = "我的BGT余额：" + snatchData.getBgtNum();
        SpannableString bgtText = MyTextUtils.getInstance().setAutoTextColor(bgt, "[0-9.]{1,}", "#FF5453");
        tv_items_balance.setText(bgtText);
    }

    private void initEvent() {
        //选择框点击事件处理
        gv_items_choose.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                String number = chooseData.get(position).getNumber();
                //bgt可购买的最大数量
                int total = (int) (snatchData.getGoodsPrice() * snatchData.getBgtNum());
                if (TextUtils.equals("全部", number)) {
                    //判断bgt数量是否足够买全部, 能则显示剩余数, 否则显示bgt可购买的最大数量
                    et_items_num.setText(String.valueOf(total > canBought ? canBought : total));
                } else {
                    et_items_num.setText(number);
                }
            }
        });
        //减操作
        tv_items_subtract.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String trim = et_items_num.getText().toString().trim();
                if (TextUtils.isEmpty(trim)) {
                    et_items_num.setText(String.valueOf(0));
                } else {
                    int anInt = Integer.parseInt(trim);
                    et_items_num.setText(String.valueOf(anInt > 0 ? anInt - 1 : 0));
                }
            }
        });
        //加操作
        tv_items_add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (snatchData == null) {
                    return;
                }
                String trim = et_items_num.getText().toString().trim();
                if (TextUtils.isEmpty(trim)) {
                    if (canBought > 0) {
                        et_items_num.setText(String.valueOf(1));
                    }
                } else {
                    int anInt = Integer.parseInt(trim);
                    if (anInt < canBought) {
                        et_items_num.setText(String.valueOf(anInt + 1));
                    }
                }
            }
        });

        //立即下单
        tv_items_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (ordersClickListener != null) {
                    String num = et_items_num.getText().toString().trim();
                    int count = 0;
                    if (!TextUtils.isEmpty(num)) {
                        count = Integer.parseInt(num);
                    }
                    //在提交订单时判断bgt数量是否足够购买当前选择的商品
                    if (snatchData != null) {
                        int needBgt = (int) (count * snatchData.getGoodsPrice());
                        int myBgt = (int) snatchData.getBgtNum();
                        if (needBgt > myBgt) {
                            Toast.makeText(mActivity, "您的BGT数量不足...", Toast.LENGTH_SHORT).show();
                            return;
                        }
                    }
                    ordersClickListener.ordersClick(count, count * snatchData.getGoodsPrice(), snatchData.getPeriodId());
                }
            }
        });
    }

    /**
     * 显示popupwindow
     */
    public void showPopupWindow() {
        if (this.isShowing()) {
            this.dismiss();
        } else {
            backgroundAlpha(0.5f);
            int[] location = new int[2];
            view.getLocationOnScreen(location);
            this.showAtLocation(view, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, -location[1]);
        }
    }

    /**
     * 设置添加屏幕的背景透明度
     *
     * @param bgAlpha
     */
    public void backgroundAlpha(float bgAlpha) {
        WindowManager.LayoutParams lp = mActivity.getWindow().getAttributes();
        lp.alpha = bgAlpha; //0.0-1.0
        mActivity.getWindow().setAttributes(lp);
        mActivity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
    }

    private OnOrdersClickListener ordersClickListener;

    public interface OnOrdersClickListener {
        /**
         * 抢购事件
         *
         * @param count  抢购份数
         * @param expend 共消耗BGT数量
         */
        void ordersClick(int count, int expend, int periodId);
    }
}
